var http = require('http'),
    fs = require('fs'),
    url = require('url'),
    mime = require('mime'),
    formidable = require('formidable');
http.createServer(function(req, res) {
    var urlObj = url.parse(req.url, true),
        pathname = urlObj.pathname;
    if (pathname == '/') {
        res.setHeader('Content-type', 'text/html;charset=utf8');
        fs.createReadStream('./index.html').pipe(res);
    } else if (pathname == '/upload') {
        // formidable 第三方模块
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
            fs.createReadStream(files.content.path).pipe(fs.createWriteStream('./upload/' + files.content.name));
        });
        form.on('end', function() {
            res.end('文件已经上传成功!!!');
        });
    } else {
        fs.exists('.' + pathname, function(flag) {
            if (flag) {
                res.setHeader('Content-Type', mime.getType(pathname) + ';charset=utf8');
                fs.createReadStream('.' + pathname).pipe(res);
            } else {
                res.statusCode = 404;
                res.end('not found');
            }
        })
    }
}).listen(8080);
